package com.l9lou.creeper.cupule;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * author: eric
 * Date: 11-7-26
 * Time: 下午2:34
 */
public class DataPool {

    private List<Map<String, Object>> pool = new CopyOnWriteArrayList<Map<String, Object>>();

    private int readIndex;
    private int writeIndex;
    private int markedReadIndex;
    private int markedWriteIndex;

    /**
     * 这里使用list作为容器，因此不必考虑数组的容量问题
     * @param colaCans
     */
    public void write(List<Map<String, Object>> colaCans){
        takeReadableDataTo(colaCans);
        restoreIndexesToDefault();
    }

    private void restoreIndexesToDefault() {
        readIndex = 0;
        writeIndex = 0;
    }

    private void takeReadableDataTo(List<Map<String, Object>> colaCans) {
        for(int idx = readIndex; idx < writeIndex; idx++){
            colaCans.add(this.pool.get(idx));
        }
    }

    public void read(List<Map<String, Object>> data){
        pool.addAll(data);
        this.writeIndex = pool.size()-1;
    }



    public void markReadIndex(){
        this.markedReadIndex = this.readIndex;
    }

    public void markWriteIndex(){
        this.markedWriteIndex = this.writeIndex;
    }

    public int readableSize(){
        return (this.writeIndex - this.readIndex);
    }

    public int size(){
        return this.pool.size();
    }

    public int getReadIndex() {
        return readIndex;
    }

    public void setReadIndex(int readIndex) {
        this.readIndex = readIndex;
    }

    public int getWriteIndex() {
        return writeIndex;
    }

    public void setWriteIndex(int writeIndex) {
        this.writeIndex = writeIndex;
    }
}
